package com.xyz.service.impl;

import cn.hutool.core.date.DateUtil;
import com.xyz.entity.mapper.*;
import com.xyz.entity.pojo.*;
import com.xyz.service.CommonService;
import com.xyz.service.RoleAppService;
import com.xyz.util.dto.DataResult;
import com.xyz.util.dto.LoginInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Service
@Transactional(rollbackFor = Exception.class)
public class RoleAppServiceImpl implements RoleAppService {

    @Autowired
    private CommonService commonService;

    @Autowired
    private SystemRoleDirectoryAppMapper systemRoleDirectoryAppMapper;

    @Autowired
    private SystemEmployeeMapper systemEmployeeMapper;

    @Override
    public DataResult selectAppUserInfo(LoginInfo li) throws Exception {
        SystemEmployee se = systemEmployeeMapper.selectByPrimaryKey(li.getLoginEmployeeId());
        Map<String, Object> map = new HashMap<>();
        map.put("username", li.getLoginUsername());
        map.put("roleName", li.getLoginRoleName());
        map.put("employeeName", se.getEmployeeName());
        map.put("phoneNumber", se.getPhoneNumber());
        map.put("positionName", commonService.getDictMap("TYPE_EMPLOYEE_POSITION").getOrDefault(se.getPosition(), ""));
        map.put("headFileCode", se.getHeadFileCode());
        map.put("isMessage", se.getIsMessage());
        map.put("loginTime", DateUtil.formatDateTime(li.getLoginTime()));
        map.put("lastLoginTime", DateUtil.formatDateTime(li.getLastLoginTime()));
        map.put("directory", commonService.getDirectory(2, li.getLoginRoleId()));
        return DataResult.build9100(map);
    }

    @Override
    public DataResult selectAppDirectoryByRoleId(LoginInfo li, long roleId) throws Exception {
        return DataResult.build9100(commonService.getDirectory(3, roleId));
    }

    @Override
    public DataResult updateAppDirectoryByRoleId(LoginInfo li, long roleId, String directoryIds) throws Exception {
        if (roleId == 1L) {
            return DataResult.build9250("超级管理员无法修改或删除");
        }
        List<Long> directoryIdList = new ArrayList<>();
        for (String directoryId : directoryIds.split(",")) {
            directoryIdList.add(Long.parseLong(directoryId));
        }

        SystemRoleDirectoryAppExample srdaExample = new SystemRoleDirectoryAppExample();
        srdaExample.createCriteria().andRoleIdEqualTo(roleId);
        systemRoleDirectoryAppMapper.deleteByExample(srdaExample);

        SystemRoleDirectoryApp newSrda = new SystemRoleDirectoryApp();
        for (long directoryId : directoryIdList) {
            newSrda.setRoleId(roleId);
            newSrda.setDirectoryId(directoryId);
            systemRoleDirectoryAppMapper.insert(newSrda);
        }

        return DataResult.build9100();
    }

}
